package com.wjv.example.springboot.base.filter;

import com.wjv.example.common.JsonHelper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>Title: LogRecordAspect</p>
 *
 * 请求信息日志切面处理
 *
 * @author wjv
 * @date Create in 2021/3/18 10:44
 */
@Slf4j
@Aspect
@Configuration
public class LogRecordAspect {

    // 定义切点Pointcut，所有controller类都会经过切面
    @Pointcut("execution(* com.wjv.example..controller..*Controller.*(..))")
    public void executionService() {
    }

    @Around("executionService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String method = request.getMethod();
        String uri = request.getRequestURI();
        String contentType = request.getContentType();
        String queryString = JsonHelper.toJson(request.getParameterMap());

        if (HttpMethod.POST.name().equals(method) && null != contentType) {
            // post请求中，仅对json和xml进行解析
            if (contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)
                    || contentType.startsWith(MediaType.APPLICATION_XML_VALUE)) {
                queryString = new RequestWrapper(request).getBody();
            }
        }
        log.debug("请求: {}->{}, 参数: {}", method, uri, queryString);

        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();

        log.debug("返回: {}", JsonHelper.toJson(result));
        return result;
    }
}
